package com.cy.milktea.controller;


import com.cy.milktea.pojo.System.JsonResult;
import com.cy.milktea.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;



@RestController
public class ShiroController {

    @RequestMapping("/login")
    public JsonResult login(String username, String password) {
        if (username == null || password == null) return JsonResult.error("参数为空!");

        UsernamePasswordToken upToken = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(upToken);
        User user = (User) subject.getPrincipal();
        User newUser = new User();
        //返回前端需要的参数
        newUser.setId(user.getId());
        newUser.setName(user.getName());
        newUser.setUsername(user.getUsername());
        newUser.setRoleId(user.getRoleId());
        return JsonResult.ok("登录成功!", newUser);
    }

    @RequiresAuthentication
    @RequestMapping("/logout")
    public JsonResult logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        return JsonResult.ok("成功退出!");
    }
}
